from flask import Blueprint, request, jsonify
from app.models import DetectionEvent
from app.extensions import db
from datetime import datetime
from app.utils.geo_utils import update_street_names  # 导入街道名更新工具
from routes.auth import token_required

# 创建蓝图，统一前缀/api/v1
detection_bp = Blueprint('detection', __name__, url_prefix='/api/v1')


@detection_bp.route('/detections', methods=['POST'])
@token_required
def add_detection(current_user_id):
    """接收AI引擎发送的垃圾检测数据并存储"""
    data = request.json  # 获取JSON数据

    try:
        # 解析检测时间（确保格式正确）
        detect_time = datetime.strptime(data['detect_time'], '%Y-%m-%d %H:%M:%S')

        # 创建检测事件记录
        event = DetectionEvent(
            class_=data['class'],
            conf=data['conf'],
            x1=data['x1'],
            y1=data['y1'],
            x2=data['x2'],
            y2=data['y2'],
            lat=data.get('lat'),
            lng=data.get('lng'),
            timestamp=data['timestamp'],
            frame_index=data['frame_index'],
            detect_time=detect_time
        )

        db.session.add(event)
        db.session.commit()

        # 异步更新街道名
        update_street_names()

        return jsonify({'code': 201, 'message': '数据保存成功', 'event_id': event.id})

    except KeyError as e:
        return jsonify({'code': 400, 'error': f'缺少必要字段：{str(e)}'}), 400
    except Exception as e:
        db.session.rollback()  # 出错回滚
        return jsonify({'code': 500, 'error': f'服务器错误：{str(e)}'}), 500